package com.xcity.db.type;

import java.sql.CallableStatement;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;

import org.apache.ibatis.type.BaseTypeHandler;
import org.apache.ibatis.type.JdbcType;

import com.alibaba.fastjson.JSON;
import com.xcity.game.buildv2.BuildManagerV2;
import com.xcity.game.buildv2.BuildV2;

import naga.x.util.StringUtils;

public class BuildsV2TypeHandler extends BaseTypeHandler<BuildManagerV2> {
	
	@Override
	public void setNonNullParameter(PreparedStatement ps, int i, BuildManagerV2 parameter, JdbcType jdbcType)
			throws SQLException {
		ps.setString(i, parameter != null ? parameter.toString() : null);
	}

	@Override
	public BuildManagerV2 getNullableResult(ResultSet rs, String columnName) throws SQLException {
		return parse(rs.getString(columnName));
	}

	@Override
	public BuildManagerV2 getNullableResult(ResultSet rs, int columnIndex) throws SQLException {
		return parse(rs.getString(columnIndex));
	}

	@Override
	public BuildManagerV2 getNullableResult(CallableStatement cs, int columnIndex) throws SQLException {
		return parse(cs.getString(columnIndex));
	}
	
	private static BuildManagerV2 parse(String json) {
		if (StringUtils.isEmpty(json)) {
			return null;
		}
		String[] strs = StringUtils.split(json, ";");
		if(strs.length == 3){
			return new BuildManagerV2(null, JSON.parseArray(strs[0], BuildV2.class), (int) JSON.parse(strs[1]), JSON.parseArray(strs[2], Long.class));
		}
		return new BuildManagerV2(null, JSON.parseArray(json, BuildV2.class), 0, null);
	}

}
